<template>
	<div>
		<a-row :gutter="10">
			<a-col :xs="24" :sm="24" :md="24" :lg="5" :xl="5">
				<a-card :bordered="false" >
					<a-tree
						v-if="treeData.length > 0"
						:defaultExpandAll="true"
						:tree-data="treeData"
						:field-names="treeFieldNames"
						@select="treeSelect"
					>
					</a-tree>
				</a-card>
			</a-col>

			<a-col :xs="24" :sm="24" :md="24" :lg="19" :xl="19">
				<a-card :bordered="false">
					<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
						<a-row :gutter="24">
							<a-col :span="6">
								<a-form-item label="编码" name="productCode">
									<a-input v-model:value="searchFormState.productCode" placeholder="请输入编码" />
								</a-form-item>
							</a-col>
							<a-col :span="6">
								<a-form-item label="名称" name="productName">
									<a-input v-model:value="searchFormState.productName" placeholder="请输入名称" />
								</a-form-item>
							</a-col>
							<a-col :span="6">
								<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
								<a-button style="margin: 0 8px" @click="reset">重置</a-button>
							</a-col>
						</a-row>
					</a-form>
					<s-table
						ref="tableRef"
						:columns="columns"
						:data="loadData"
						:alert="options.alert.show"
						bordered
						:row-key="(record) => record.productId"
						:tool-config="toolConfig"
						:row-selection="options.rowSelection"
					>
						<template #operator class="table-operator">
							<a-space>
								<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('imsProductAdd')">
									<template #icon><plus-outlined /></template>
									新增
								</a-button>

								<a-button @click="batchModal.onOpen()">
									<template #icon><import-outlined /></template>
									<span>{{ $t('common.imports') }}</span>
								</a-button>
								<a-button @click="exportBatchUser">
									<template #icon><export-outlined /></template>
									{{ $t('user.batchExportButton') }}
								</a-button>

								<xn-batch-delete
									v-if="hasPerm('imsProductBatchDelete')"
									:selectedRowKeys="selectedRowKeys"
									@batchDelete="deleteBatchImsProduct"
								/>
							</a-space>
						</template>
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'productType'">
								{{ record.productTypeName }}
							</template>
							<template v-if="column.dataIndex === 'measureUnit'">
								{{ $TOOL.dictTypeData('unit', record.measureUnit) }}
							</template>
							<template v-if="column.dataIndex === 'status'">
								{{ $TOOL.dictTypeData('COMMON_STATUS', record.status) }}
							</template>
							<template v-if="column.dataIndex === 'action'">
								<a-space>
									<a @click="formRef.onOpen(record)" v-if="hasPerm('imsProductEdit')">编辑</a>
									<a-divider type="vertical" v-if="hasPerm(['imsProductEdit', 'imsProductDelete'], 'and')" />
									<a-popconfirm title="确定要删除吗？" @confirm="deleteImsProduct(record)">
										<a-button type="link" danger size="small" v-if="hasPerm('imsProductDelete')">删除</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
					</s-table>
				</a-card>

			</a-col>

		</a-row>



		<Form ref="formRef" @successful="tableRef.refresh()" />



		<xn-form-container title="导入导出" :width="700" :visible="batchModal.visible" :destroy-on-close="true" @close="batchModal.onClose">
		<span>导入数据格式严格按照系统模板进行数据录入，请点击
			<a-button type="primary" size="small" @click="batchModal.downloadImportUserTemplate">下载模板</a-button>
		</span>
			<a-divider dashed />
			<div>
				<a-spin :spinning="batchModal.impUploadLoading">
					<a-upload-dragger :show-upload-list="false" :custom-request="batchModal.customRequestLocal" :accept="batchModal.uploadAccept">
						<p class="ant-upload-drag-icon">
							<inbox-outlined></inbox-outlined>
						</p>
						<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
						<p class="ant-upload-hint">仅支持xls、xlsx格式文件</p>
					</a-upload-dragger>
				</a-spin>
			</div>
			<a-alert v-if="batchModal.impAlertStatus" type="info" :show-icon="false" banner closable @close="batchModal.onImpClose" class="mt-3">
				<template #description>
					<p>导入总数：{{ batchModal.impResultData.totalCount }} 条</p>
					<p>导入成功：{{ batchModal.impResultData.successCount }} 条</p>
					<div v-if="batchModal.impResultData.errorCount > 0">
						<p><span class="xn-color-red">失败条数：</span>{{ batchModal.impResultData.errorCount }} 条</p>
						<a-table :dataSource="batchModal.impResultErrorDataSource" :columns="batchModal.impErrorColumns" size="small" />
					</div>
				</template>
			</a-alert>
		</xn-form-container>



	</div>


</template>

<script setup name="basics">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import Form from './form.vue'
	import imsProductApi from '@/api/ims/imsProductApi'
	import imsProductTypeApi from "@/api/ims/imsProductTypeApi";




	import downloadUtil from '@/utils/downloadUtil'



	// 批量导入
	const batchModal = ref({
		visible: false,
		impUploadLoading: false,
		impAlertStatus: false,
		impResultData: false,
		impResultErrorDataSource: false,


		onOpen: () => {
			batchModal.value.visible = true
		},
		// 关闭抽屉
		onClose: () => {
			batchModal.value.visible = false
			// 关闭导入的提示
			batchModal.value.onImpClose()
			tableRef.value.refresh()
		},
		// 下载用户导入模板
		downloadImportUserTemplate :() => {
			imsProductApi.downloadImportTemplate().then((res) => {
				downloadUtil.resultDownload(res)
			})
		},
		// 指定能选择的文件类型
		uploadAccept : String(
			[
				{
					extension: '.xls',
					mimeType: 'application/vnd.ms-excel'
				},
				{
					extension: '.xlsx',
					mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				}
			].map((item) => {
				return item.mimeType
			})
		),
		impErrorColumns :[
			{
				title: '索引',
				dataIndex: 'index',
				width: '80px'
			},
			{
				title: '原因',
				dataIndex: 'msg'
			}
		],
		impAccept : [
			{
				extension: '.xls',
				mimeType: 'application/vnd.ms-excel'
			},
			{
				extension: '.xlsx',
				mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
			}
		],
		// 关闭导入提示
		onImpClose : () => {
			batchModal.value.impAlertStatus = false
		},
		customRequestLocal : (data) => {
			batchModal.value.impUploadLoading = true
			const fileData = new FormData()
			// 校验上传文件扩展名和文件类型是否为.xls、.xlsx
			const extension = '.'.concat(data.file.name.split('.').slice(-1).toString().toLowerCase())
			const mimeType = data.file.type
			// 提取允许的扩展名
			const extensionArr = batchModal.value.impAccept.map((item) => item.extension)
			// 提取允许的MIMEType
			const mimeTypeArr = batchModal.value.impAccept.map((item) => item.mimeType)
			if (!extensionArr.includes(extension) || !mimeTypeArr.includes(mimeType)) {
				message.warning('上传文件类型仅支持xls、xlsx格式文件！')
				batchModal.value.impUploadLoading = false
				return false
			}
			fileData.append('file', data.file)
			return imsProductApi
				.import(fileData)
				.then((res) => {
					batchModal.value.impAlertStatus = true
					batchModal.value.impResultData = res
					batchModal.value.impResultErrorDataSource = res.errorDetail

					tableRef.value.refresh()
				})
				.finally(() => {
					batchModal.value.impUploadLoading = false
				})
		}
	})
	// 批量导出
	const exportBatchUser = () => {
		imsProductApi.export().then((res) => {
			downloadUtil.resultDownload(res)
			tableRef.value.clearSelected()
		})
	}





	const defaultExpandedKeys = ref([])
	const treeData = ref([])
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }

	const searchFormState = ref({})
	const searchFormRef = ref()
	const tableRef = ref()
	const formRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const columns = [
		{
			title: '商品编码',
			dataIndex: 'productCode'
		},
		{
			title: '商品名称',
			dataIndex: 'productName'
		},
		{
			title: '商品类型',
			dataIndex: 'productType'
		},
		{
			title: '商品规格',
			dataIndex: 'productSpecifications'
		},
		{
			title: '商品品牌',
			dataIndex: 'brand'
		},
		{
			title: '计量单位',
			dataIndex: 'measureUnit'
		},
		{
			title: '成本价',
			dataIndex: 'costPrice'
		},
		{
			title: '销售价格',
			dataIndex: 'univalence'
		},
		{
			title: '物品条码',
			dataIndex: 'productBarcode'
		},
		{
			title: '库存数量',
			dataIndex: 'inventoryQty'
		},
		{
			title: '默认仓库',
			dataIndex: 'defaultWarehouse'
		},
		{
			title: '备注',
			dataIndex: 'remark'
		},
		{
			title: '保质期',
			dataIndex: 'expirationDate'
		},
		{
			title: '状态',
			dataIndex: 'status'
		},
	]
	// 操作栏通过权限判断是否显示
	if (hasPerm(['imsProductEdit', 'imsProductDelete'])) {
		columns.push({
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 150
		})
	}
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				console.log('选择行：', selectedRowKey)
				selectedRowKeys.value = selectedRowKey
			}
		}
	}


	// 点击树查询
	const treeSelect = (selectedKeys) => {
		if (selectedKeys.length > 0) {
			searchFormState.value.productTypeId = selectedKeys.toString()
		} else {
			delete searchFormState.value.productTypeId
		}
		tableRef.value.refresh(true)
	}
	const loadData = (parameter) => {
		const searchFormParam = cloneDeep(searchFormState.value)

		// 加载分类
		imsProductTypeApi.productTypeTree(searchFormParam).then(res => {
			treeData.value = res
		})

		return imsProductApi.imsProductPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}
	// 删除
	const deleteImsProduct = (record) => {
		let params = [
			{
				id: record.productId
			}
		]
		imsProductApi.imsProductDelete(params).then(() => {
			tableRef.value.refresh(true)
		})
	}
	// 批量删除
	const deleteBatchImsProduct = (params) => {
		imsProductApi.imsProductDelete(params).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}
</script>
